package ltd.dujiabao.eduoss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import ltd.dujiabao.eduoss.service.FileService;
import ltd.dujiabao.eduoss.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author : DuJiabao
 * @Project : online-course-project
 * @Time : 2021/4/20 20:03
 * @Desc :
 */
@Service
public class FileServiceImpl implements FileService {
  @Override
  public String upload(MultipartFile file) {
    String endpoint = ConstantPropertiesUtil.ENDPOINT;
    String accessKeyId = ConstantPropertiesUtil.KEYID;
    String accessKeySecret = ConstantPropertiesUtil.KEYSECRET;
    String bucketname = ConstantPropertiesUtil.BUCKETNAME;

    // 创建OSSClient实例。
    OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

    InputStream inputStream = null;
    try {
      inputStream = file.getInputStream();
    } catch (IOException e) {
      e.printStackTrace();
    }
    // 保存的文件名
    String fileName = UUID.randomUUID().toString().replaceAll("-", "") + file.getOriginalFilename();
    String dataTime = new DateTime().toString("yyyy/MM/dd/");
    ossClient.putObject(bucketname, dataTime + fileName, inputStream);

    // 关闭OSSClient。
    ossClient.shutdown();
    // 返回url
    return "https://" + bucketname + "." + endpoint + "/" + dataTime + fileName;
  }
}
